
import gtk
import os 
from ..balancer import __file__ as base

import re

# The icon that represents us
BASE_ICON = "coins"

def __path(suffix):
    """Determine the path that we expect the resource directories to live at."""
    return os.path.dirname(os.path.dirname(base)) + "/resources/" + suffix + "/"

def icon_list(name):
    """Retrieve all sizes of the named icon."""
    path = __path(name)

    icons = []

    if os.path.isdir(path):
        for p in os.listdir(path):
            if p.endswith(".png"):
                full = path + "/" + p
                buf = gtk.gdk.pixbuf_new_from_file(full)
                icons.append(buf)

    return icons


def icon(name, size=16):
    """Retrieve a specific size of the named icon."""
    path = __path(name)

    suffix = "-%s.png" % size
    if os.path.isdir(path):
        for p in os.listdir(path):
            if p.endswith(suffix):
                full = path + "/" + p
                return gtk.gdk.pixbuf_new_from_file(full)

    return None


def sized_icon(name, max_size):
    """Retrieve the largest icon that is smaller than the given size"""
    path = __path(name)

    regex = re.compile(r"-(\d+).png$")

    best_num = 0
    best = None
    if os.path.isdir(path):
        for p in os.listdir(path):
            match = regex.search(p)
            if not match:
                continue

            candidate = int(match.group(1))
                
            if candidate > max_size:
                continue

            if candidate < best_num:
                continue

            best_num = candidate
            best = path + "/" + p
            
    if best:
        return gtk.gdk.pixbuf_new_from_file(best)

    return None
